<template>
    <MyNav />
    <div class="account">
        <div class="account-info">
            <div class="inner">
                <div class="user-info">
                    <div class="avatar-uploader">
                        <el-upload accept="image/png, image/jpg, image/jpeg" :show-file-list="false"
                            :before-upload="uploadAvatar" :http-request="httpRequest" action="javascript:;">
                            <!-- <template #file> -->
                            <div class="ava-box">
                                <el-avatar :size="80" :src="circleUrl" />
                                <div class="ava-edit"></div>
                            </div>
                            <!-- </template> -->
                        </el-upload>
                    </div>
                    <div class="user-detail">
                        <div class="name">
                            <div class="name-text">{{ userInfo.userName }}</div>
                            <button @click="openInfoEdit">
                                <span class="icon"></span>
                                <span class="text">修改密码</span>
                            </button>
                        </div>
                    </div>
                    <div class="btns">
                        <div class="btn-logout" @click="logout"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="acc-container">
            <ul class="tabs">
                <li class="tab" :class="{ active: currentTab === 'proBox' }" @click="changeTab('proBox')">藏品</li>
                <!-- <li class="tab" :class="{ active: currentTab === 'sell' }" @click="changeTab('sell')">已卖出</li>
                <li class="tab" :class="{ active: currentTab === 'release' }" @click="changeTab('release')">已发布</li> -->
            </ul>
            <div class="main-content" v-loading="loading">
                <div class="pro-box">
                    <el-card v-for="item in userGoodsList" :key="item._id" :body-style="{ padding: '0px' }"
                        shadow="always" class="productList">
                        <!-- 图片区域 -->
                        <div class="media-wrapper">
                            <!-- 图片懒加载 -->
                            <img v-lazy="item.shopImg" class="image" alt="..." />
                            <!-- 查看详情 -->
                            <div class="btn-status">
                                <button @click="() => { router.push(`/detail/${item._id}`) }">
                                    <span>查看详情</span>
                                    <span class="icon"></span>
                                </button>
                            </div>
                        </div>
                        <!-- 图片结束 -->

                        <!-- 文字、价格 -->
                        <div style="padding: 14px">
                            <span class="album-name">{{ item.shopName }}</span>
                            <span class="icon"></span>
                            <!-- 价格 -->
                            <div class="bottom">
                                <el-button class="button white" type="primary" plain
                                    @click="showSellModal(item)">转售</el-button>
                            </div>
                        </div>
                    </el-card>
                    <el-empty v-if="!userGoodsList.length" style="width: 100%;" description="您尚未拥有藏品" />
                </div>
            </div>
        </div>
    </div>
    <MyFoot />
    <el-dialog v-model="showInfoEdit" title="修改密码" width="30%" :before-close="handleClose">
        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px" style="padding-right: 40px;">
            <el-form-item label="手机号">
                <el-input v-model="form.tel" disabled />
            </el-form-item>
            <el-form-item label="原密码" prop="oldPass">
                <el-input v-model="form.oldPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPass">
                <el-input v-model="form.newPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认新密码" prop="rePass">
                <el-input v-model="form.rePass" type="password" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelInfoEdit(ruleFormRef)">取消</el-button>
                <el-button type="primary" @click="infoEditConfirm(ruleFormRef)">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog v-model="showSellPrice" title="输入售价" width="320" :before-close="hideSellModal">
        <span style="font-size: 24px;">￥</span>
        <el-input v-model.trim.number="inpSellPrice" style="width: 220px;margin-left: 10px;" />
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="hideSellModal">取消</el-button>
                <el-button type="primary" @click="sellUGoods">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, getCurrentInstance, ComponentInternalInstance, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, UploadRawFile } from 'element-plus'
import MyNav from '../components/MyNav.vue';
import MyFoot from '../components/MyFoot.vue';
import { getUserInfo, updateUserPass, getUserGoods, getGoodsDetail, sellUserGoods } from '../api/api';

// 表单接口约束
interface InfoFormType {
    tel: string;
    oldPass: string;
    newPass: string;
    rePass: string;
}
// 用户信息接口约束
interface UserInfoType {
    _id: string;
    __v: number;
    userName?: string | null;
    phone: number;
    password: string;
}
// 用户藏品接口约束
interface UserGoodsType {
    _id: string;
    shopName: string;
    shopImg: string;
}

// ctx 打包后在生产环境下是获取不到的
// 要使用 const { proxy } = getCurrentInstance()
// getCurrentInstance 结合 ts 使用时会报错，可添加类型约束解决
const { proxy }: any = getCurrentInstance() as ComponentInternalInstance

// 获取全局状态
const store = useStore()
// 获取路由对象
const router = useRouter()

const circleUrl = ref<any>('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 用户信息
const userInfo = ref<UserInfoType>({
    _id: '',
    __v: 0,
    userName: '',
    phone: 0,
    password: ''
})

// 用户拥有的藏品
const userGoodsList = ref<UserGoodsType[]>([])

// 加载用户藏品状态
const loading = ref(false)
// 转售价格
const inpSellPrice = ref('')
// 转售价格输入弹出框显示状态
const showSellPrice = ref(false)
// 藏品id
const proId = ref('')

// 表单ref
const ruleFormRef = ref<FormInstance>()
// 用户信息修改表单
const form = reactive<InfoFormType>({
    tel: '',
    oldPass: '',
    newPass: '',
    rePass: ''
})
// 自定义检验规则
const validateoOldPass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('原密码不能为空！'))
    }
    callback()
}

const validateNewPass = (rule: any, value: any, callback: any) => {
    // 验证密码 6至15位的字母+数字
    let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,15}$/

    if (value === '') {
        callback(new Error('新密码不能为空！'))
    } else {
        if (!reg.test(value)) {
            callback(new Error('密码格式有误!必须为6至15位的字母+数字'))
        }
        if (form.rePass != '') {
            if (!ruleFormRef.value) return
            ruleFormRef.value.validateField('rePass', () => null)
        }
        callback()
    }
}

const validateRePass = (rule: any, value: any, callback: any) => {
    if (value != form.newPass) {
        callback(new Error("两次密码输入不一致！"))
    } else {
        callback()
    }
}
// 表单校验规则
const rules = reactive({
    oldPass: [
        {
            validator: validateoOldPass,
            trigger: 'blur'
        }
    ],
    newPass: [
        {
            validator: validateNewPass,
            trigger: 'blur'
        }
    ],
    rePass: [
        {
            validator: validateRePass,
            trigger: 'blur'
        }
    ]
})

// 当前激活tab
const currentTab = ref('proBox')

// 用户信息编辑弹出框显示状态
const showInfoEdit = ref(false)


onMounted(async () => {
    // 请求用户信息
    if (store.state._token) {
        let res: any = await getUserInfo(store.state.userId)
        // console.log(res);
        if (res.data.errorCode === 405 || res.data.errorCode === 401 || res.data.errorCode === 402) {
            ElMessage({
                message: res.data.msg + '，请重新登录！',
                type: 'error',
                duration: 1500,
                onClose: () => {
                    router.push('/login')
                }
            })
        } else if (res.data.errorCode === 0) {
            userInfo.value = res.data.data.info
        }

        getUGoodsData()
    } else {
        ElMessage({
            message: '您需要先登录才能操作！',
            type: 'error',
            duration: 1500,
            onClose: () => {
                router.push('/login')
            }
        })
    }
})


// 获取用户藏品
const getUGoodsData = async () => {
    userGoodsList.value = []
    let arr: any[] = []
    loading.value = true
    let goods: any = await getUserGoods(store.state.userId)
    // console.log(goods)
    if (goods.data.data && goods.data.data.length) {
        goods.data.data.forEach((item: any) => {
            arr.push(getGoodsDetail(item.shopId))
        })
        let resArr = await Promise.all(arr)
        // console.log(resArr)
        resArr.forEach((item: any) => {
            userGoodsList.value.push({
                _id: item.data.data.data._id,
                shopName: item.data.data.data.shopName,
                shopImg: item.data.data.data.shopImg
            })
        })
    }
    loading.value = false
}


// 切换tab
const changeTab = (name: string) => {
    if (currentTab.value != name) currentTab.value = name
}

// 打开用户信息修改弹出框
const openInfoEdit = () => {
    showInfoEdit.value = true
    form.tel = userInfo.value.phone + ''
}

// 确认修改
const infoEditConfirm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            console.log('submit!')
            let obj = {
                oldpass: form.oldPass,
                newpass: form.newPass
            }
            // console.log(obj);
            let res: any = await updateUserPass(store.state.userId, 'PUT', obj)
            console.log(res);
            if (res.data.errorCode === 0) {
                ElMessage({
                    message: res.data.message + '，将重新登录',
                    type: 'success',
                    onClose: () => {
                        store.commit('userLogout')
                        router.push('/login')
                    }
                })
            } else if (res.data.errorCode === 2 || res.data.errorCode === 3) {
                ElMessage({
                    message: res.data.message,
                    type: 'error'
                })
            } else {
                ElMessage({
                    message: '请求发生错误',
                    type: 'error'
                })
            }
        } else {
            console.log('验证不通过！')
            return false
        }
    })
}

// 关闭用户信息修改弹出框
const handleClose = (done: () => void) => {
    proxy?.$refs.ruleFormRef.resetFields()
    done()
}
const cancelInfoEdit = (formEl: FormInstance | undefined) => {
    showInfoEdit.value = false
    formEl?.resetFields()
}

// 显示转售价格输入
const showSellModal = (item: any) => {
    showSellPrice.value = true
    proId.value = item._id
}
// 关闭转售价格输入
const hideSellModal = () => {
    showSellPrice.value = false
    inpSellPrice.value = ''
}
// 出售藏品
const sellUGoods = () => {
    if (!inpSellPrice.value) {
        ElMessage({
            message: '请输入价格！',
            type: 'error',
            duration: 1500
        })
        return
    } else if (isNaN(Number(inpSellPrice.value))) {
        ElMessage({
            message: '请输入整数数字作为价格！',
            type: 'error',
            duration: 1500
        })
        return
    }
    ElMessageBox.confirm('确定要转售吗？', {
        title: '提示',
        type: 'info',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: async (action: any) => {
            if (action === 'confirm') {
                let res: any = await sellUserGoods({
                    userId: store.state.userId,
                    shopId: proId.value,
                    shopPrice: inpSellPrice.value
                })
                if (res.data.errorCode === 0) {
                    ElMessage({
                        message: '成功转售！',
                        type: 'success',
                        duration: 1500
                    })
                    inpSellPrice.value = ''
                    showSellPrice.value = false
                    getUGoodsData()
                } else if (res.data.errorCode === 401 || res.data.errorCode === 405) {
                    ElMessage({
                        message: res.data.msg + '，请重新登录！',
                        type: 'error',
                        duration: 1500,
                        onClose: () => {
                            router.push('/login')
                        }
                    })
                } else {
                    ElMessage({
                        message: '请求错误！',
                        type: 'error',
                        duration: 1500
                    })
                }
            }
        }
    })
}

// 用户退出登录
const logout = () => {
    ElMessageBox.confirm('确定要退出吗？', {
        title: '提示',
        type: 'info',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: (action: any) => {
            if (action === 'confirm') {
                store.commit('userLogout')
                ElMessage({
                    message: '成功退出！',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        router.push('/index')
                    }
                })
            }
        }
    })
}

// 上传头像
const uploadAvatar = (rawFile: UploadRawFile) => {
    console.log(rawFile);
    let rd = new FileReader() // 创建文件读取对象
    rd.readAsDataURL(rawFile)
    rd.onloadend = function (e) {
        // console.log(this.result);
        circleUrl.value = this.result
    }
}
// 上传头像请求（假）,用于覆盖upload组件默认的上传请求，避免报错
const httpRequest = (data: any) => {
    // console.log(data);
    // let rd = new FileReader() // 创建文件读取对象
    // rd.readAsDataURL(data.file)
    // rd.onloadend = async function (e) {
    //     console.log(this.result);
    //     let res = await request('/banans/api/upload', 'POST', {
    //         img: this.result
    //     })
    // }
}

</script>

<style lang='scss' scoped>
.account {
    min-width: 1200px;

    .account-info {
        padding: 50px 0;
        background: #2c2c34;

        .inner {
            padding: 0 30px;

            // 用户信息
            .user-info {
                display: flex;
                align-items: center;
                margin-bottom: 30px;

                // 用户头像
                .ava-box {
                    margin-right: 20px;
                    position: relative;

                    .ava-edit {
                        width: 23px;
                        height: 23px;
                        position: absolute;
                        right: 0;
                        bottom: 0;
                        background: url(https://www.ibox.art/zh-cn/static/img/95a0a62.v1669810212431.png) 50% no-repeat;
                    }
                }

                // 用户手机号和编辑按钮
                .user-detail {
                    flex: 1;
                    color: #fff;

                    .name {
                        margin-bottom: 8px;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        -webkit-box-pack: start;
                        -webkit-box-align: center;

                        .name-text {
                            font-weight: 700;
                            font-size: 26px;
                            line-height: 36px;
                        }

                        button {
                            flex-shrink: 0;
                            background: hsla(0, 0%, 100%, .1);
                            height: 34px;
                            padding: 0 14px;
                            color: #fff;
                            border-radius: 17px;
                            font-size: 14px;
                            line-height: 20px;
                            margin-left: 18px;
                            border: none;
                            cursor: pointer;

                            .icon {
                                width: 16px;
                                height: 16px;
                                display: inline-block;
                                background: url(https://www.ibox.art/zh-cn/static/img/9b1dbf0.v1669810212431.svg) 50% no-repeat;
                            }

                            span {
                                vertical-align: middle;
                            }
                        }
                    }
                }

                .btns {
                    align-self: flex-end;

                    .btn-logout {
                        width: 80px;
                        height: 34px;
                        background: url(https://www.ibox.art/zh-cn/static/img/7309e09.v1669810212431.png) no-repeat 50%/100% 100%;
                        cursor: pointer;
                    }
                }
            }
        }
    }

    // 主内容区域
    .acc-container {
        padding: 0 15px;

        // tab切换样式
        .tabs {
            margin: 0;
            padding: 0;
            list-style: none;

            .tab {
                display: inline-block;
                height: 56px;
                min-width: 166px;
                padding: 0 30px;
                text-align: center;
                font-size: 16px;
                line-height: 56px;
                color: #2c2c34;
                cursor: pointer;
            }

            .tab.active {
                background: #2c2c34;
                color: #fff;
            }
        }

        .main-content {
            padding: 50px 0;

            .pro-box {
                display: flex;
                flex-wrap: wrap;

                // 商品列表样式开始
                .productList {
                    position: relative;
                    margin: 10px;
                    height: 400px;
                    width: 270px;

                    // 文字区域
                    .album-name {
                        font: 600 18px/26px "";
                        height: 26px;
                        overflow: hidden;
                        color: #14181f;
                        display: inline-block;
                        -o-text-overflow: ellipsis;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        cursor: pointer;
                    }

                    .icon {
                        display: inline-block;
                        width: 16px;
                        height: 20px;
                        line-height: 26px;
                        background: url(https://www.ibox.art/zh-cn/static/img/04e21d6.v1669810212431.svg) center 50% no-repeat;
                    }

                    // 价格
                    .bottom {
                        margin-top: 13px;
                        line-height: 12px;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        margin-top: 8px;

                        .button {
                            margin-left: auto;
                            min-width: 60px;
                            height: 36px;
                            padding: 6px 8px;
                            font-size: 17px;
                            display: flex;
                            border-radius: 6px;

                        }

                        .white {
                            border: 2px solid #2c2c34;
                            background-color: #fff;
                            color: #2c2c34;
                            cursor: default;
                        }

                        // .card-num {
                        //     line-height: 18px;
                        //     color: #87888e;
                        //     font-size: 14px;
                        // }
                    }

                    .button:hover {
                        border-color: #2c2c34;
                        background: #2c2c34;
                        color: #fff;
                        opacity: .8;
                        cursor: pointer;
                    }

                    // 图片区域
                    .media-wrapper {
                        height: 100%;
                        overflow: hidden;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        position: relative;
                        transition: all 0.3s;

                        //   图片区域
                        .image {
                            width: 100%;
                            height: 300px;
                            display: block;
                        }

                        // 按钮开始
                        .btn-status {
                            position: absolute;
                            left: 0;
                            right: 0;
                            top: 50%;
                            margin-top: -28px;
                            height: 56px;
                            text-align: center;
                            display: none;

                            button {
                                height: 100%;
                                width: 228px;
                                background: rgba(44, 44, 52, .67);
                                border: 1px solid #fff;
                                font-size: 18px;
                                line-height: 25px;
                                display: inline-block;
                                color: #fff;
                                -webkit-border-radius: 10px;
                                -moz-border-radius: 10px;
                                border-radius: 10px;
                                cursor: pointer;

                                .text {
                                    display: inline-block;
                                    vertical-align: middle;

                                }

                                .icon {
                                    width: 25px;
                                    height: 25px;
                                    background-image: url(../assets/proListimage/3.png);
                                    background-position: center center;
                                    background-repeat: no-repeat;
                                    background-size: 100%;
                                    margin-left: 8px;
                                    vertical-align: middle;

                                }
                            }

                            //  按钮结束
                        }
                    }

                    //鼠标滑动效果
                    .media-wrapper:hover img {
                        transform: translateZ(30px) translateY(1px) scale(1.3);
                        filter: blur(2px);
                    }

                    .media-wrapper:hover .btn-status {
                        display: block;
                    }
                }
            }
        }
    }
}

// 用户信息编辑弹出框
.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>